package pers.jing.android.helper.widget

import androidhelper.composeapp.generated.resources.Res
import androidhelper.composeapp.generated.resources.device
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.material3.ElevatedCard
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.VerticalDivider
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.RectangleShape
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.window.Dialog
import org.jetbrains.compose.resources.stringResource
import org.koin.compose.viewmodel.koinViewModel
import pers.jing.android.helper.model.DeviceInfo
import pers.jing.android.helper.model.STATE_DIALOG_CONFIRM

/**
 * 首次打开弹窗, 会触发一次更新, 此时设备列表是空, 等拿到设备之后会在更新一次
 */
@Composable
fun InstallApkDialog(
    viewModel: InstallApkViewModel = koinViewModel<InstallApkViewModel>(),
    apkPath: String,
    onDismiss: () -> Unit) {
    val deviceList = viewModel.getStateFlowDevices().collectAsState()
    println("InstallApkDialog ${deviceList.value.size}")
    var curApkPath by remember {
        mutableStateOf(apkPath)
    }
    var curDeviceIndex by remember {
        mutableStateOf(0)
    }

    val progressDialogState = viewModel.progressDialogState.collectAsState()
    val dialogState = viewModel.dialogState.collectAsState()
    Dialog(
        onDismissRequest = {

        }
    ) {
        ElevatedCard(
            modifier = Modifier.width(400.dp)
        ) {
            Column(
                modifier = Modifier.fillMaxWidth(),
                horizontalAlignment = Alignment.CenterHorizontally
            ) {
                Text(
                    text = "安装APK",
                    fontSize = 17.sp,
                    fontWeight = FontWeight.Bold,
                    modifier = Modifier.padding(top = 10.dp)
                )

                Spinner(
                    name = stringResource(Res.string.device),
                    placeHolder = "",
                    data = deviceList.value.map {
                        it.getDeviceName()
                    },
                    selectedIndex = curDeviceIndex,
                    modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp)
                ) { index, text ->
                    curDeviceIndex = index
                }

                OutlinedFileField(
                    title = "选择APK",
                    filePath = curApkPath,
                    ext = ".apk",
                    modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp)) {
                    curApkPath = it
                }
                HorizontalDivider(
                    modifier = Modifier.fillMaxWidth()
                        .padding(top = 10.dp)
                )
                Row(
                    verticalAlignment = Alignment.CenterVertically,
                    modifier = Modifier.fillMaxWidth()
                ) {
                    TextButton (
                        shape = RectangleShape,
                        onClick = {
                            onDismiss()
                        },
                        modifier = Modifier.weight(1.0f)) {
                        Text(
                            text = "取消",
                            color = MaterialTheme.colorScheme.tertiary
                        )
                    }
                    VerticalDivider(
                        modifier = Modifier.height(30.dp)
                    )
                    TextButton (
                        shape = RectangleShape,
                        onClick = {
                            viewModel.install(curDeviceIndex, curApkPath)
                        },
                        modifier = Modifier.weight(1.0f),
                    ) {
                        Text(
                            text = "安装",
                            color = MaterialTheme.colorScheme.primary
                        )
                    }
                }
            }
        }
    }
    if (progressDialogState.value.show) {
        ProgressDialog(text = "正在安装")
    }
    if (STATE_DIALOG_CONFIRM == dialogState.value.state) {
        //弹窗
        ConfirmDialog(msg = dialogState.value.msg?:"unknown", onDismiss = {
            val nextStep = dialogState.value.nextStep
            viewModel.closeConfirmDialog()
            if ("closeInstallApkDialog" == nextStep) {
                onDismiss()
            }
        }, onConfirm = {
            //仅在安装成功之后, 点击我知道了, 关闭安装APK的弹窗
            val nextStep = dialogState.value.nextStep
            viewModel.closeConfirmDialog()
            if ("closeInstallApkDialog" == nextStep) {
                onDismiss()
            }
        })
    }

}

private fun checkOkEnabled(index: Int, deviceList: List<DeviceInfo>, apkPath: String): Boolean {
    println("checkOkEnabled: $index, ${deviceList.size}")
    return index >= 0 && index < deviceList.size
            && apkPath.isNotEmpty()
            && apkPath.isNotBlank()
}